// NewSupportCommand.cpp: implementation of the NewSupportCommand class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "NewSupportCommand.h"
#include "PipeGenerator.h"
#include "SupportHangerGenerator.h"
#include "ProjectManager.h"
#include "SupportHangerManager.h"
#include "SHPoint.h"
#include "GeometryObjectGenerator.h"
#include "AllSHIDViewer.h"
#include <dbmain.h>
#include <migrtion.h>
#include "AutoCADGMS.h"
#include "PHSDirectorySetting.h"
#include "PHSApp.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

NewSupportCommand::NewSupportCommand()
{
	this->m_pSupportHanger = NULL;
	this->m_pPipe = NULL;
	this->m_strBlockName = GetCurDirectorySetting().PrjTemplateDir() + GetPHSApp()->SHDefaultBlock();
}

NewSupportCommand::~NewSupportCommand()
{

}

BOOL NewSupportCommand::Execute()
{	
	if(!NewSupportHanger())
		return FALSE;
	return NewSupportHangerPoint();
}

void NewSupportCommand::GetPipeObject()
{
	m_pPipe = PipeGenerator::Instance()->Generate();
	ASSERT(m_pPipe);
}

BOOL NewSupportCommand::NewSupportHanger()
{
	m_pSupportHanger = GetSupportHangerGenerator().NewSupportHanger();
	if(m_pSupportHanger == NULL)
		return FALSE;

	ASSERT(GetProjectManager().CurProject());
	m_pSupportHanger->BlockName(m_strBlockName);
	m_pSupportHanger->GetSupportHangerPoint().Database(
		GetProjectManager().CurProject()->ProjectSource());
	m_pSupportHanger->GetSupportHangerPoint().PrjID(
		GetProjectManager().CurProject()->ProjectName());
	m_pSupportHanger->project(GetProjectManager().CurProject());

	return TRUE;
}

BOOL NewSupportCommand::NewSupportHangerPoint()
{
	ASSERT(m_pSupportHanger);

	AutoCADGMS* pGMS = AutoCADGMS::GetCurGMS();

	SHObserverManager& manager = pGMS->GetSHObserverManager();
	
	CString strKey = m_pSupportHanger->SupportHangerID();
	SHPoint pPt;
	pPt = manager.GetSHPoint(strKey);
	pPt.Model(m_pSupportHanger);

	if(!pPt.Create(m_pSupportHanger->BlockName()))
	{
		manager.Remove(m_pSupportHanger);
		delete m_pSupportHanger;
		return FALSE;
	}

	GetPipeObject();
	SupportHangerManager& SHManager = GetProjectManager().CurProject()->GetSupportHangerManager();
	SHManager.AddSupportHanger(m_pSupportHanger);
	AllSHIDViewer::Instance()->AddSupportHanger(m_pSupportHanger->SupportHangerID());
	m_pSupportHanger->AddPart(m_pPipe);
	m_pSupportHanger->SupportHangerEntry(m_pPipe);

	pPt.Update();
	m_pSupportHanger->ModelMatrix(pPt.Matrix());

	return TRUE;
}